<template>
  <div class="app-container ohn transaction-box">
    <div class="f22 pointer" @click="goBack()">
      <i class="el-icon-arrow-left" />【{{ testTrade.name }}】测试工作单
    </div>
    <el-divider class="mt50" content-position="left">基本信息</el-divider>
    <el-form
      ref="worksheetCreateFrom"
      v-loading="formLoading"
      class="mt36"
      :inline="true"
      :model="worksheetCreateFrom"
      status-icon
      :rules="rules"
      label-width="150px"
    >
      <el-form-item :label="'报告编号\nClient'" prop="workOrderNum">
        <el-input
          v-model="worksheetCreateFrom.workOrderNum"
          placeholder="请输入报告编号"
          clearable
        />
      </el-form-item>
      <el-form-item :label="'开单人\nAttn'" prop="issuer">
        <el-input
          v-model="worksheetCreateFrom.issuer"
          placeholder="请输入开单人"
          clearable
        />
      </el-form-item>
      <el-form-item :label="'加急情况\nAgree to subcontract'" prop="busyStatus">
        <el-radio-group v-model="worksheetCreateFrom.busyStatus">
          <el-radio label="50%加急" />
          <el-radio label="100%加急" />
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="'开单时间\nDate'" prop="gmtCreate">
        <el-date-picker
          v-model="worksheetCreateFrom.gmtCreate"
          type="date"
          placeholder="请选择开单时间"
          style="width: 206px"
        />
      </el-form-item>
      <el-form-item :label="'出单时间\nDate'" prop="gmtOutput">
        <el-date-picker
          v-model="worksheetCreateFrom.gmtOutput"
          type="date"
          placeholder="请选择出单时间"
          style="width: 206px"
        />
      </el-form-item>
      <el-form-item :label="'是否退样\nAgree to subcontract'" prop="withdraw">
        <el-radio-group v-model="worksheetCreateFrom.withdraw">
          <el-radio label="否" />
          <el-radio label="退样" />
        </el-radio-group>
      </el-form-item>
      <el-divider content-position="left">样品单明细</el-divider>

      <vxe-toolbar ref="xToolbar">
        <template #tools>
          <el-button type="primary" size="small" plain @click="insertEvent"
            >新增</el-button
          >
        </template>
      </vxe-toolbar>
      <vxe-table
        ref="xTable"
        border
        show-footer
        show-overflow
        class="editable-footer mb20"
        :merge-footer-items="mergeFooterItems"
        :row-config="{ isHover: true }"
        :export-config="{}"
        :footer-cell-class-name="footerCellClassName"
        :data="worksheetCreateFrom.testWorkOrderItemList"
        :edit-config="{ trigger: 'click', mode: 'row' }"
        @edit-closed="editClose"
      >
        <vxe-column type="seq" width="60" :title="'序号\nNum'" align="right" />
        <vxe-column
          field="sampleDesc"
          :title="'样品描述\nSampleDesc'"
          :edit-render="{}"
        >
          <template #edit="{ row }">
            <vxe-input v-model="row.sampleDesc" type="text" />
          </template>
        </vxe-column>
        <vxe-column
          field="sampleLocation"
          :title="'取样部位(位置)\nSampleLocation'"
          :edit-render="{ autofocus: '.vxe-input--inner' }"
          width="160"
        >
          <template #edit="{ row }">
            <vxe-input
              v-model="row.sampleLocation"
              type="text"
              :min="1"
              :max="120"
              @change="updateFooterEvent"
            />
          </template>
        </vxe-column>
        <vxe-column
          field="testItemsMethod"
          :title="'测试项目及测试方法\nTestItemsMethod'"
          :edit-render="{ autofocus: '.vxe-input--inner' }"
        >
          <template #edit="{ row }">
            <vxe-input
              v-model="row.testItemsMethod"
              type="text"
              @input="updateFooterEvent"
            />
          </template>
        </vxe-column>

        <vxe-column
          field="remark"
          :title="'备注\nremark'"
          :edit-render="{ autofocus: '.vxe-input--inner' }"
        >
          <template #edit="{ row }">
            <vxe-input
              v-model="row.remark"
              type="text"
              @input="updateFooterEvent"
            />
          </template>
        </vxe-column>
        <vxe-column title="操作" width="80">
          <template #default="{ row }">
            <el-button type="text" status="primary" @click="deleteEvent(row)"
              >删除</el-button
            >
          </template>
        </vxe-column>
      </vxe-table>

      <el-form-item>
        <div class="tr">
          <el-button
            v-loading="formLoading"
            type="primary"
            @click="submitForm('worksheetCreateFrom')"
            >保存</el-button
          >
          <el-button @click="resetForm('worksheetCreateFrom')">重置</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import methods from "./pub_methods/validate";
export default {
  data() {
    return {
      formLoading: false,
      testTrade: {
        name: "",
        id: "",
        status: "",
      },
      rules: methods.quotationCreateValidate,
      worksheetCreateFrom: {
        testTradeId: undefined,
        workOrderNum: "bj123456",
        issuer: "北京小王",
        busyStatus: "100%加急",
        gmtCreate: "2022-07-11 23:35:40",
        gmtOutput: "2022-07-15 12:00:00",
        withdraw: "否",
        employee: "销售小李",
        customer: "北京烤鸭老吴",
        testWorkOrderItemList: [
          {
            sampleDesc: "金黄烤鸭",
            sampleLocation: "鸭子嘴",
            testItemsMethod: "用金刚石测试鸭子嘴硬度",
            remark: "分包",
          },
        ],
      },
      mergeFooterItems: [
        { row: 0, col: 0, rowspan: 0, colspan: 8 },
        // { row: 0, col: 1, rowspan: 9, colspan: 9 },
      ],
      customerOptions: [
        { key: 1, value: "中文纸质档" },
        { key: 2, value: "中文电子档" },
        { key: 3, value: "英文电子档" },
        { key: 4, value: "英文纸质档" },
      ],
      allowAdd: true,
    };
  },
  created() {
    this.testTrade.name = this.$route.query.name;
    this.testTrade.id = this.$route.query.id;
    this.testTrade.status = this.$route.query.status;
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.worksheetCreateFrom.testTradeId = this.testTrade.id;
          const insertData = this.$refs.xTable.getRecordset();
          this.worksheetCreateFrom.testWorkOrderItemList =
            insertData.insertRecords;
          if (this.worksheetCreateFrom.testWorkOrderItemList.length === 0) {
            this.$message.warning("请填写报价单明细");
          } else {
            this.formLoading = true;
            this.$store
              .dispatch(
                "transaction/saveTestWorkOrder",
                this.worksheetCreateFrom
              )
              .then((res) => {
                const { data, success, errorMessage } = res;
                if (success) {
                  this.$refs[formName].resetFields();
                  this.$message.success(data.msg);
                } else {
                  this.$message.error(errorMessage);
                }
              })
              .catch(() => {})
              .finally(() => {
                this.formLoading = false;
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.worksheetCreateFrom.testWorkOrderItemList = [];
      this.$refs[formName].resetFields();
    },
    goBack() {
      this.$router.push({
        path: "/detection/list",
      });
    },
    footerCellClassName({ $rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        if ($rowIndex === 0) {
          return "col-blue";
        }
      }
      if (columnIndex === 2) {
        if ($rowIndex === 1) {
          return "col-red";
        }
      }
    },
    // 在值发生改变时更新表尾合计
    updateFooterEvent() {
      const $table = this.$refs.xTable;
      $table.updateFooter();
    },
    async insertEvent(row) {
      if (this.allowAdd) {
        const record = {
          sampleDesc: "",
          sampleLocation: "",
          testItemsMethod: "",
          remark: "",
        };
        const { row: newRow } = await this.$refs.xTable.insert(record, row);
        await this.$refs.xTable.setActiveCell(newRow, "productDes");
      }
    },
    // 编辑单元格事件
    async editClose({
      row,
      rowIndex,
      $rowIndex,
      column,
      columnIndex,
      $columnIndex,
    }) {
      const errMap = await this.$refs.xTable
        .validate(true)
        .catch((errMap) => errMap);
      if (errMap) {
        this.allowAdd = false;
      } else {
        this.allowAdd = true;
      }
    },
    deleteEvent(row) {
      this.$confirm("您确定要删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$refs.xTable.remove(row);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.transaction-box {
  .el-form .el-form-item__label {
    background-color: red;
    line-height: 20px !important;
  }
  .el-form-item--medium .el-form-item__label {
    line-height: 20px !important;
  }
  .remark-content {
    font-size: 12px;
    color: #808080;
    line-height: 20px;
  }
}
</style>
